<?php
/**
 * 产品工具类
 *
 * 产品工具类
 *
 * @author    zhouchao <zhouchao@yunys.com.cn>
 * @copyright 2016 QuanZhouYunYiShang Inc.
 */
namespace App\Services\ProductsService;

use App\Services\BaseService;
use App\Services\ProductsService\ProductTrait\product_trait;
use App\Services\ProductTempService\ProductTempTool;
use App\Services\SourcePicService\SourcePicTool;
use App\Services\Exceptions\EntityNotFoundException;
use App\Services\FontService\FontService;
use App\Services\GiftService\GiftApiService;
use App\Services\Tool\GeneralTool;
use App\Services\ColourService\ColourTool;
use App\Services\PreferentialService\PreferentialService;
use App\Services\Exceptions\ImageNotFoundException;
use App\Services\Exceptions\PriceErrorException;
use App\Services\Exceptions\FontNotFoundException;
use DB;
use Log;

class ProductTool extends BaseService
{

    use product_trait;

    protected $product_temp_tool;
    protected $source_pic_tool;
    protected $font;

    public function __construct(ProductTempTool $product_temp_tool, SourcePicTool $source_pic_tool, FontService $font)
    {
        $this->product_temp_tool = $product_temp_tool;
        $this->source_pic_tool = $source_pic_tool;
        $this->font = $font;
    }

    /**
     * 根据用户ID用户用户产品数量
     * @param $user_id
     * @return mixed
     */
    public function getProductNumByUserID($user_id, $current_user_id=0)
    {
        $this->setParameter(array(
            'table' => 'products',
            'where' => array(
                array('user_id', '=', $user_id),
                array('is_shelves', '=', 1),
                array('state', '=', 1)
            ),
        ));
        if($user_id != $current_user_id){
            $this->where[] = ['is_show','=',1];
        }
        $product_num = $this->count();
        return $this->numFormat($product_num);
    }

    /**
     * 数字格式化
     */
    public function numFormat($number)
    {
        if ($number < 999) {
            return $number;
        }
        if (1000 <= $number || 9999 > $number) {
            return round(($number / 1000), 1) . 'k';
        }
        if (10000 <= $number || 999999 > $number) {
            return round(($number / 10000), 1) . 'w';
        }
        if (1000000 <= $number || 9999999 > $number) {
            return round(($number / 100000), 1) . 'm';
        }
    }

    /**
     * 创建默认作品集
     * @param $user_id
     * @return mixed
     */
    public function createDefaultCollections($user_id)
    {
        $this->setParameter([
            'table' => 'user_collections',
            'where' => [['user_id', '=', $user_id], ['is_default', '=', 1], ['state', '=', 1]],
            'select' => 'collection_id'
        ]);
        $user_collection = $this->getById();
        if (!empty($user_collection)) {
            return true;
        }
        //创建默认作品集
        $input['collection_name'] = '默认作品集';
        $input['collection_id'] = GeneralTool::only_no();
        $input['is_default'] = 1;
        $input['user_id'] = $user_id;
        //封面
        $input['original_image'] = 'collection_default_cover.png';
        $input['thumbnail'] = 'collection_default_cover.png';
        $input['created_at'] = $input['updated_at'] = time();
        $result = DB::table('user_collections')->insert($input);
        return $result;
    }

    /**
     * 下架用户的所有作品
     * @param $user_id
     */
    public function shelve_products_by_user_id($user_id)
    {
        $this->setParameter([
            'table' => 'products',
            'where' => [['user_id', '=', $user_id], ['is_shelves', '=', 1]]
        ]);
        $update_arr = array('is_shelves' => 0, 'updated_at' => time());
        $result = $this->update($update_arr);
        return $result;
    }

    /**
     * 获取用户作品
     * @param $user_id
     * @param int $per_page
     * @return array
     */
    public function getProductsByUserId($user_id, $per_page = 10,$current_user_id=0)
    {
        try {
            $this->setParameter(array(
                'table' => 'products',
                'where' => array(
                    array('user_id', '=', $user_id),
                    array('state', '=', 1),
                    array('is_shelves', '=', 1)
                ),
                'select' => array('product_id', 'product_temp_id', 'colour_id', 'overflow_price', 'title', 'description', 'dig_num', 'collect_num','price as original_price','preferential_price'),
                'order' => 'created_at',
                'sort' => 'desc'
            ));
            if($user_id != $current_user_id){
                $this->where[] = ['is_show','=',1];
            }
            $products = $this->getAllPaginated($per_page)->toArray();
            foreach ($products['data'] as $product) {
                //获取价格
                //$price_arr = $this->getTotalPrice($product);
                $product->original_price = GeneralTool::priceFormat($product->original_price);
                $product->preferential_price = GeneralTool::priceFormat($product->preferential_price);
                $product->has_preferential = $product->original_price == $product->preferential_price ? 0 : 1;
                $this->get_product_preview_images($product);
            }
            return array('total_page' => $products['last_page'], 'per_page' => $per_page, 'current_page' => $products['current_page'], 'data' => $products['data']);
        } catch (\Exception $e) {
            Log::info($e);
            return array('total_page' => 0, 'per_page' => $per_page, 'current_page' => 1, 'data' => array());
        }
    }

    /**
     * 获取收藏作品
     * @param $product_id
     * @return mixed
     */
    public function get_favorite_products($product_id)
    {
        $this->setParameter(array(
            'table' => 'products',
            'where' => [['product_id', '=', $product_id]],
            'select' => ['product_id', 'state', 'is_shelves']
        ));
        $product = $this->getById();
        if (!empty($product)) {
            $this->get_product_preview_images($product);
        }
        return $product;
    }

    /**
     * 根据产品ID获取模板ID
     * @param $product_id
     * @return bool
     */
    public function getTemplateByProductId($product_id)
    {
        $this->setParameter(array(
            'table' => 'products',
            'where' => array(
                array('product_id', '=', $product_id)
            ),
            'select' => array('product_temp_id')
        ));
        $product = $this->getById();
        if (empty($product)) {
            return false;
        }
        return $product->product_temp_id;
    }

    /**
     * 根据模板ID获取品牌ID
     * @param $product_temp_id
     */
    public function get_brand_id_by_prod_temp_id($product_temp_id)
    {
        return $this->product_temp_tool->getBrandIdByProdTempId($product_temp_id);
    }

    /**
     * 添加收藏数量
     * @param $resource_id
     * @param $num
     * @return mixed
     */
    public function addCollectNum($resource_id, $num)
    {
        return DB::table('products')
            ->where('product_id', $resource_id)
            ->increment('collect_num', $num);
    }

    /**
     * 取消收藏-1
     * @param $create_id
     * @param $num
     * @return mixed
     */
    public function minusCollectNum($resource_id, $num)
    {
        return DB::table('products')
            ->where('product_id', $resource_id)
            ->decrement('collect_num', $num);
    }

    /**
     * 订单详情列表所需参数
     * @param $product_id
     * @param $quantity
     * @return null
     */
    public function get_product_detail_for_order($product_id, $quantity, $colour_name, $size, $type = 1)
    {
        try {
            //获取产品
            $this->setParameter(array(
                'table' => 'products',
                'where' => array(
                    array('product_id', '=', $product_id)
                ),
                'select' => array('product_id', 'product_temp_id', 'is_shelves', 'user_id', 'colour_id',
                    'overflow_price','stock','is_infinite_stock','price as original_price','preferential_price')
            ));
            $product = $this->getById();
            if (empty($product)) {
                return $this->createResult('M08001', (object)array());
            }
            $product = $this->get_product_preview_images($product);
            //计算产品价格
            //$prices = $this->getTotalPrice($product);
            //计算总的价格
            $product->original_price = GeneralTool::priceFormat($product->original_price);
            $product->preferential_price = GeneralTool::priceFormat($product->preferential_price);
            $total_price = bcmul($quantity, $product->preferential_price, 2);
            //Todo(获取库存)
//            $product_stock = ProductTempTool::getStock($product->product_temp_id,$colour_name,$size);
//            if(empty($product_stock)){
//                $product->stock = 0;
//            }
            if($product->is_infinite_stock == 1){
                //不限数量
                $product->stock = 999;
            }
            //使用这个价格获取赠品
            $product->gift = GiftApiService::getProductGift(['product_id' => $product->product_id, 'total_fee' => $total_price]);
            //模板信息
            $product_temp = $this->product_temp_tool->getProdTempDetailByProdTempId($product->product_temp_id, $product->colour_id,0);
            if (empty($product_temp)) {
                return $this->createResult('M08010', $product);
            }
//            $modify_price = ModifyResourcePriceRecordsService::is_resource_modify_price($product->product_temp_id,$product->colour_id,2);
//            if($modify_price !== false){
//                $product_temp->preferential_price = $product_temp->original_price == $product_temp->preferential_price ? GeneralTool::priceFormat($modify_price) : $product_temp->preferential_price;
//                $product_temp->original_price = GeneralTool::priceFormat($modify_price);
//            }
            $product->product_temp = $product_temp;
            if ($type == 2) {
                //获取使用的素材ID
                $source_pic_ids = $this->getReSourceIds(
                    array(
                        array('product_id', '=', $product->product_id),
                        array('type', '=', 1),
                        array('image_type', '=', 2),
                        array('state', '=', 1)
                    ),
                    'creative_id'
                );
                $source_pic_ids = array_unique($source_pic_ids);
                $source_pics = array();
                foreach ($source_pic_ids as $source_pic_id) {
                    $source_pic = $this->source_pic_tool->getSourcePicDetail($source_pic_id);
//                    $modify_price = ModifyResourcePriceRecordsService::is_resource_modify_price($source_pic_id,0,1);
//                    if($modify_price !== false){
//                        $source_pic->preferential_price = $source_pic->original_price == $source_pic->preferential_price ? GeneralTool::priceFormat($modify_price) : $source_pic->preferential_price;
//                        $source_pic->original_price = GeneralTool::priceFormat($modify_price);
//                    }
                    $source_pics[] = $source_pic;
                }
                //获取使用的自定义素材
                $custom_source_pic_ids = $this->getReSourceIds(
                    array(
                        array('product_id', '=', $product->product_id),
                        array('type', '=', 1),
                        array('image_type', '=', 1),
                        array('state', '=', 1)
                    ),
                    'creative_id'
                );
                $custom_source_pic_ids = array_unique($custom_source_pic_ids);
                foreach ($custom_source_pic_ids as $custom_source_pic_id) {
                    $source_pics[] = $this->get_custom_source_pic($custom_source_pic_id);
                }

                //获取使用的字体ID
                $font_ids = $this->getReSourceIds(
                    array(
                        array('product_id', '=', $product->product_id),
                        array('type', '=', 2),
                        array('state', '=', 1)
                    ),
                    'font_id'
                );
                $font_ids = array_unique($font_ids);
                foreach ($font_ids as $font_id) {
                    $font = $this->font->get_font_by_id($font_id);
//                    $modify_price = ModifyResourcePriceRecordsService::is_resource_modify_price($font_id,0,3);
//                    if($modify_price !== false){
//                        $font->preferential_price = $font->original_price == $font->preferential_price ? GeneralTool::priceFormat($modify_price) : $font->preferential_price;
//                        $font->original_price = GeneralTool::priceFormat($modify_price);
//                    }
                    $source_pics[] = $font;
                }
                $product->source_pics = $source_pics;
            }
            //获取打印ID
            $this->setParameter([
                'table' => 'product_preview_images',
                'where' => [['product_id','=',$product->product_id],['state','=',1]],
                'select'=> ['product_preview_image_id','position_type']
            ]);
            //$product->product_preview_image_ids = $this->pluck('product_preview_image_id')->toArray();
            $product->product_preview_image_ids = $this->getAll()->toArray();
            return $this->createResult('M00000', $product);
        } catch (\Exception $e) {
            Log::info($e);
            return $this->createResult('M08009', (object)array());
        }
    }

    /**
     * 根据ID获取预览图和打印图
     * @param $product_preview_image_id
     * @return mixed
     */
    public function get_product_preview_images_by_id($product_preview_image_id){
        $product_preview_images = DB::table('product_preview_images')->where(['product_preview_image_id'=>$product_preview_image_id])->first();
        return $product_preview_images;
    }

    /**
     * 存打印图片
     * @param $product_preview_image_id
     * @param $product_print_image
     * @param $product_print_thumbnail_image
     * @return mixed
     */
    public function save_product_print_image_by_id($product_preview_image_id,$product_print_image,$product_print_thumbnail_image){
        $result = DB::table('product_preview_images')
            ->where('product_preview_image_id',$product_preview_image_id)
            ->insert(['product_print_image'=>$product_print_image,'product_print_thumbnail_image'=>$product_print_thumbnail_image,'updated_at'=>time()]);
        return $result;
    }

    /**
     * 根据product_id获取实际价格
     * @param $product_id
     * @return array
     */
    public function get_preferential_price_by_product_id($product_id)
    {
        try {
            $this->setParameter(array(
                'table' => 'products',
                'where' => array(
                    array('product_id', '=', $product_id)
                ),
                'select' => array('product_id', 'product_temp_id', 'user_id', 'colour_id', 'overflow_price','price as original_price','preferential_price')
            ));
            $product = $this->getById();
            if (empty($product)) {
                return 0;
            }
            //计算产品价格
            //$prices = $this->getTotalPrice($product);
            return GeneralTool::priceFormat($product->preferential_price);
        } catch (\Exception $e) {
            Log::info($e);
            return 0;
        }
    }

    /**
     * 修改库存
     * @param $product_id
     * @param $num
     * @param int $type
     * @return array
     */
    public static function product_stock_change($product_id, $num, $type = 1)
    {
        $product = DB::table('products')
            ->where([['product_id','=',$product_id]])
            ->select('is_infinite_stock', 'stock')
            ->first();
        if (empty($product)) {
            return 0;
        }
        if ($product->is_infinite_stock == 1) {
            //不限数量
            return 1;
        }
        if ($type == 1) {
            //增加
            $flag = DB::table('products')
                ->where('product_id', $product_id)
                ->increment('stock', $num);
        } else {
            //判断库存
            if ($product->stock < $num) {
                $num = $product->stock;
            }
            $flag = DB::table('products')
                ->where('product_id', $product_id)
                ->decrement('stock', $num);
        }
        return $flag;
    }

    /**
     * 修改已售数量
     * @param $product_id
     * @param $num
     * @param int $type
     * @return array
     */
    public function product_sell_num($product_id, $num, $type = 1)
    {
        $this->setParameter(array(
            'table' => 'products',
            'where' => array(
                array('product_id', '=', $product_id)
            ),
            'select' => array('sell_num')
        ));
        $product = $this->getById();
        if (empty($product)) {
            return 0;
        }
        if ($type == 1) {
            $flag = DB::table('products')
                ->where('product_id', $product_id)
                ->increment('sell_num', $num);
        } else {
            if ($product->sell_num < $num) {
                $num = $product->sell_num;
            }
            $flag = DB::table('products')
                ->where('product_id', $product_id)
                ->decrement('sell_num', $num);
        }
        return $flag;
    }

    /**
     * 判断是否可以下单
     * @param $product_id
     * @param $colour_name
     * @param $size
     * @param $num
     * @return bool
     */
    public function can_order($product_id, $colour_name, $size, $num, $user_id)
    {
        $this->setParameter(array(
            'table' => 'products',
            'where' => array(
                array('product_id', '=', $product_id), array('state', '=', 1)
            ),
            'select' => array(
                'user_id', 'product_temp_id', 'colour_id', 'is_shelves', 'stock','price','preferential_price',
                'is_infinite_stock','is_infinite_time','off_shelves_time','prod_md5'
            )
        ));
        $product = $this->getById();
        //$state,$result,$lang='globalcodes',$add_message='',$type=1
        if(empty($product)){
            return $this->createResult('M08001', (object)array());
        }
        $product_temp = $this->product_temp_tool->getProdTempDetailByProdTempId($product->product_temp_id, $product->colour_id,0);
        if(empty($product_temp)){
            return $this->createResult('M12003',(object)array());
        }
        if($product->price == 0 || $product->preferential_price == 0){
            return $this->createResult('M08024', (object)array(),'globalcodes',$product_temp->brand_name. $product_temp->product_temp_name,1);
        }
        if($product_temp->state != 1){
            //模板删除
            return $this->createResult('M08027',(object)array(),'globalcodes',$product_temp->brand_name. $product_temp->product_temp_name,1);
        }
        //判断下架状态
        if($product->is_shelves == 1 && ($product->is_infinite_time == 0 && $product->off_shelves_time < time())){
            $product->is_shelves = 0;
        }

        if(empty($product) || ($product->user_id != $user_id && $product->is_shelves == 0)){
            return $this->createResult('M08011',(object)array(),'globalcodes',$product_temp->brand_name. $product_temp->product_temp_name,1);
        }

        if ($product->is_infinite_stock != 1) {
            if($product->stock == 0){
                return $this->createResult('M08026', (object)array());
            }
            if($product->stock < $num){
                return array('message'=>$product_temp->brand_name. $product_temp->product_temp_name.'，当前限购剩余'.$product->stock.'件，您的选购数量已超过该上限，请回到购物车修改数量',
                    'result'=>(object)array(),'state'=>'M08025');
            }
        }
//      $is_product_temp_exit = ProductTempTool::productTempExistsByProdTempId($product->product_temp_id);
        $num = intval($num);
        //$num = 0;
        $has_stock = ProductTempTool::hasStock($product->product_temp_id, $colour_name, $size, $num);
        if ($has_stock === false) {
            $this->setParameter(array(
                'table' => 'products',
                'where' => array(array('prod_md5', '=', $product->prod_md5), array('is_shelves','=',1),array('state', '=', 1))
            ));
            $product_num = $this->count();
            return $product_num > 1 ? $this->createResult('M08012', (object)array(),'globalcodes','暂时没货，看看其他颜色吧～',2) :
                $this->createResult('M08012', (object)array());
        }
        return $this->is_used_source_and_font_abnormal($product_id,$product->product_temp_id);
    }

    /**
    *  判断是否可以下单(活动)
    *  新增判断是否是活动商品 
    *
    */
    public function can_order_for_activity($product_id, $colour_name, $size, $num, $user_id)
    {
         $this->setParameter(array(
            'table' => 'products',
            'where' => array(
                array('product_id', '=', $product_id), array('state', '=', 1)
            ),
            'select' => array(
                'user_id', 'product_temp_id', 'colour_id', 'is_shelves', 'stock','price','preferential_price',
                'is_infinite_stock','is_infinite_time','off_shelves_time','prod_md5'
            )
        ));
        $product = $this->getById();
        //$state,$result,$lang='globalcodes',$add_message='',$type=1
        if(empty($product)){
            return $this->createResult('M08001', (object)array());
        }
        //获取作品的主题ID
        $type_ids = DB::table('type_resources')->where(['resource_id'=>$product_id,'state'=>1])->pluck('type_id')->toArray();
        if(!in_array('12', $type_ids) || !in_array('13', $type_ids)){
            return $this->createResult('M08029', (object)array());
        }

        $product_temp = $this->product_temp_tool->getProdTempDetailByProdTempId($product->product_temp_id, $product->colour_id,0);
        if(empty($product_temp)){
            return $this->createResult('M12003',(object)array());
        }
        if($product->price == 0 || $product->preferential_price == 0){
            return $this->createResult('M08024', (object)array(),'globalcodes',$product_temp->brand_name. $product_temp->product_temp_name,1);
        }
        if($product_temp->state != 1){
            //模板删除
            return $this->createResult('M08027',(object)array(),'globalcodes',$product_temp->brand_name. $product_temp->product_temp_name,1);
        }
        //判断下架状态
        if($product->is_shelves == 1 && ($product->is_infinite_time == 0 && $product->off_shelves_time < time())){
            $product->is_shelves = 0;
        }

        if(empty($product) || ($product->user_id != $user_id && $product->is_shelves == 0)){
            return $this->createResult('M08011',(object)array(),'globalcodes',$product_temp->brand_name. $product_temp->product_temp_name,1);
        }

        if ($product->is_infinite_stock != 1) {
            if($product->stock == 0){
                return $this->createResult('M08026', (object)array());
            }
            if($product->stock < $num){
                return array('message'=>$product_temp->brand_name. $product_temp->product_temp_name.'，当前限购剩余'.$product->stock.'件，您的选购数量已超过该上限，请回到购物车修改数量',
                    'result'=>(object)array(),'state'=>'M08025');
            }
        }
//      $is_product_temp_exit = ProductTempTool::productTempExistsByProdTempId($product->product_temp_id);
        $num = intval($num);
        //$num = 0;
        $has_stock = ProductTempTool::hasStock($product->product_temp_id, $colour_name, $size, $num);
        if ($has_stock === false) {
            $this->setParameter(array(
                'table' => 'products',
                'where' => array(array('prod_md5', '=', $product->prod_md5), array('is_shelves','=',1),array('state', '=', 1))
            ));
            $product_num = $this->count();
            return $product_num > 1 ? $this->createResult('M08012', (object)array(),'globalcodes','暂时没货，看看其他颜色吧～',2) :
                $this->createResult('M08012', (object)array());
        }
        return $this->is_used_source_and_font_abnormal($product_id,$product->product_temp_id);
    }

    /**
     * 判断产品使用的素材和字体是否存在异常
     * @param $product_id
     * @param $product_temp_id
     * @return array
     */
    public function is_used_source_and_font_abnormal($product_id,$product_temp_id){
        //获取使用的素材ID
        $source_pic_ids = $this->getReSourceIds(array(
            array('product_id', '=', $product_id), array('type', '=', 1), array('image_type', '=', 2), array('state', '=', 1)
        ), 'creative_id');
        $source_pic_ids = array_unique($source_pic_ids);
        foreach ($source_pic_ids as $source_pic_id) {
            $source_pic_result = $this->source_pic_tool->getSourcePicAvailableBySourcePicIdAndProdTempId($source_pic_id,$product_temp_id,2);
            if($source_pic_result['state'] != 'M00000'){
                return $source_pic_result;
            }
        }
        //获取使用的字体ID
        $font_ids = $this->getReSourceIds(array(
            array('product_id', '=', $product_id), array('type', '=', 2), array('state', '=', 1)
        ), 'font_id');
        $font_ids = array_unique($font_ids);
        foreach ($font_ids as $font_id) {
            $font = $this->font->font_exit($font_id);
            if($font === false){
                return $this->createResult('M08020', (object)array());
            }
        }
        return $this->createResult('M00000', (object)array());
    }

    /**
     * 根据模板ID获取邮费
     * @param $product_temp_id
     * @return int|null
     */
    public function get_postage_by_product_temp_id($product_temp_id)
    {
        $package = ProductTempTool::getProdTempPostageByProdTempId($product_temp_id);

        if ($package === null) {
            Log::info('ID为' . $product_temp_id . '的模板邮费异常');
            return 0;
        }
        return $package;
    }

    /**
     * 获取模板实际金额(优惠券)
     * @param $product_id
     * @return int
     */
    public function get_product_temp_price_by_product_temp_id($product_id)
    {
        //获取产品
        $this->setParameter(array(
            'table' => 'products',
            'where' => array(
                array('product_id', '=', $product_id)
            ),
            'select' => array('product_id', 'product_temp_id', 'user_id', 'colour_id', 'overflow_price')
        ));
        $product = $this->getById();
        if (empty($product)) {
            return 0;
        }
        //模板价格 获取产品模板
        $prices = PreferentialService::getResourcePrice($product->product_temp_id, 2, $product->colour_id);
        if ($prices === false || $prices['original_price'] === false || $prices['preferential_price'] === false) {
            return 0;
        }
//        $modify_price = ModifyResourcePriceRecordsService::is_resource_modify_price($product->product_temp_id,$product->colour_id,2);
//        if($modify_price !== false){
//            $prices['preferential_price'] = $prices['original_price'] == $prices['preferential_price'] ? GeneralTool::priceFormat($modify_price) : $prices['preferential_price'];
//        }
        return GeneralTool::priceFormat($prices['preferential_price']);
    }

    /**
     * 计算产品价格区间
     * @param $product_temp_category_id
     */
    public function get_price_interval($product_temp_category_id,$cat_grade=4)
    {
        //$cat_grade = 4;
        $product_temp_ids = [];
        //排除未上架和不显示
        /* 需要价格分级 */
        /*
            算法思路：
                1、当分级大于1时，进行价格分级
                2、取出该类下商品价格的最大值、最小值
                3、根据商品价格的最大值来计算商品价格的分级数量级：
                        价格范围(不含最大值)    分级数量级
                        0-0.1                   0.001
                        0.1-1                   0.01
                        1-10                    0.1
                        10-100                  1
                        100-1000                10
                        1000-10000              100
                4、计算价格跨度：
                        取整((最大值-最小值) / (价格分级数) / 数量级) * 数量级
                5、根据价格跨度计算价格范围区间
                6、查询数据库

            可能存在问题：
                1、
                由于价格跨度是由最大值、最小值计算出来的
                然后再通过价格跨度来确定显示时的价格范围区间
                所以可能会存在价格分级数量不正确的问题
                该问题没有证明
                2、
                当价格=最大值时，分级会多出来，已被证明存在
        */
        if ($product_temp_category_id == 0) {
            //获取全部
            $max_price = DB::table('products')
                ->where([['state', '=', 1],['is_shelves','=',1],['is_show','=',1]])
                ->max('preferential_price');
            $min_price = DB::table('products')
                ->where([['state', '=', 1],['is_shelves','=',1],['is_show','=',1]])
                ->min('preferential_price');
        } else {
            $product_temp_ids = ProductTempTool::getProdTempIdsByCategoryId($product_temp_category_id);
            //根据$product_temp_ids获取所有的作品
            $this->whereIn = $product_temp_ids;
            $max_price = DB::table('products')
                ->where([['state', '=', 1],['is_shelves','=',1],['is_show','=',1]])
                ->whereIn('product_temp_id', $product_temp_ids)
                ->max('preferential_price');
            $min_price = DB::table('products')
                ->where([['state', '=', 1],['is_shelves','=',1],['is_show','=',1]])
                ->whereIn('product_temp_id', $product_temp_ids)
                ->min('preferential_price');
        }
        // 取得价格分级最小单位级数，比如，千元商品最小以100为级数
        $price_grade = 0.0001;
        for ($i = -2; $i <= log10($max_price); $i++) {
            $price_grade *= 10;
        }
        //跨度
        $dx = ceil(($max_price - $min_price) / ($cat_grade) / $price_grade) * $price_grade;
        if ($dx == 0) {
            $dx = $price_grade;
        }
        for ($i = 1; $min_price > $dx * $i; $i++) ;
        for ($j = 1; $min_price > $dx * ($i - 1) + $price_grade * $j; $j++) ;
        $min_price = $dx * ($i - 1) + $price_grade * ($j - 1);
        for (; $max_price >= $dx * $i; $i++) ;
        $max_price = $dx * ($i) + $price_grade * ($j - 1);
        if ($product_temp_category_id == 0) {
            $price_grade = DB::table('products')
                ->select(DB::raw("FLOOR((preferential_price - $min_price) / $dx) AS sn"))
                ->where([['state', '=', 1],['is_shelves','=',1],['is_show','=',1]])
                ->groupBy('sn')
                ->get()
                ->toArray();
        } else {
            $price_grade = DB::table('products')
                ->select(DB::raw("FLOOR((preferential_price - $min_price) / $dx) AS sn"))
                ->where([['state', '=', 1],['is_shelves','=',1],['is_show','=',1]])
                ->whereIn('product_temp_id', $product_temp_ids)
                ->groupBy('sn')
                ->get()
                ->toArray();
        }
        $temp_key = 0;
        foreach ($price_grade as $key => $val) {
            $start = $min_price + round($dx * $val->sn);
            $end = $min_price + round($dx * ($val->sn + 1));
            $price_grade[$temp_key]->resource_id = $start . '-' . $end;
            $price_grade[$temp_key]->search_name = $start . '-' . $end;
            $temp_key = $key + 1;
        }
        return $price_grade;

    }

    /**
     * 将某作品集下的作品转移到默认作品集
     * @param $user_id
     * @param $collection_id
     * @param $default_collection_id
     */
    public function transfer_to_default_collection($user_id, $collection_id, $default_collection_id)
    {
        //获取该作品集下的作品
        $this->setParameter(array(
            'table' => 'products',
            'where' => array(array('user_id', '=', $user_id), array('user_collection_id', '=', $collection_id)),
        ));
        $data = ['user_collection_id' => $default_collection_id, 'updated_at' => time()];
        $this->update($data);
    }

    /**
     * 获取尺码组 颜色
     */
    public function get_prod_temp_colour_size_by_product_id($product_id)
    {
        $this->setParameter([
            'table' => 'products',
            'where' => array(
                array('product_id', '=', $product_id),
                array('state', '=', 1),
            ),
            'select' => array('product_temp_id', 'colour_id')
        ]);
        $product = $this->getById();
        if (empty($product)) {
            return array();
        }
        //获取颜色
        $colour_name = ColourTool::getColourSimpleInfoByColourId($product->colour_id);
        $product->colour = $colour_name;
        //获取字码组
        $size_names = ProductTempTool::getProdTempSizesByProdTempId($product->product_temp_id);
        $product->size_names = $size_names;
        return $product;
    }

    /**
     * Todo(可以使用数据库分块处理)
     * 批量下架商品
     */
    public static function off_the_shelf(){
        Log::info('----------批量下架商品处理开始----------');
        $result = DB::table('products')
            ->where([
                ['is_shelves','=',1],
                ['is_infinite_time','=',0],
                ['off_shelves_time','<',time()],
                ['state','=',1]
            ])
            ->update(array('is_shelves'=>0,'updated_at'=>time()));
        Log::info('----------批量下架商品处理结束----------');
        return true;
    }

    /**
     * 获取产品使用明细
     * @throws FontNotFoundException
     * @throws ImageNotFoundException
     * @throws PriceErrorException
     */
    public function get_product_used_source_pic_detail($product_id,$product_temp_id)
    {
        $source = array();
        //获取设计师或者品牌商素材价格
        $source_pic_ids = $this->getReSourceIds(
            array(
                array('product_id', '=', $product_id),
                array('type', '=', 1), array('image_type', '=', 2),
                array('state', '=', 1)
            ),
            'creative_id'
        );
        $source_pic_ids = array_unique($source_pic_ids);//获取所有素材ID
        foreach ($source_pic_ids as $source_pic_id) {
            //根据ID获取素材详情
            $source_pic_result = $this->source_pic_tool->getSourcePicAvailableBySourcePicIdAndProdTempId($source_pic_id,$product_temp_id,2);
            if($source_pic_result['state'] != 'M00000'){
                throw new ImageNotFoundException('素材ID为'.$source_pic_id.',素材类型为2的原图片未找到,原因:'.$source_pic_result['message']);
            }
            $prices = PreferentialService::getResourcePrice($source_pic_id, 1);
            if ($prices === false || $prices['original_price'] === false || $prices['preferential_price'] === false) {
                throw new PriceErrorException('ID为' . $source_pic_id . '的素材价格异常');
            }
//            $modify_price = ModifyResourcePriceRecordsService::is_resource_modify_price($source_pic_id,0,1);
            $source[] = array('resource_id'=>$source_pic_id,'title'=>$source_pic_result['result']->name,'preferential_price'=>GeneralTool::priceFormat($prices['preferential_price']),'original_price'=>GeneralTool::priceFormat($prices['original_price']),'thumbnail'=>env('IMG_URL_STD_PREFIX').$source_pic_result['result']->thumbnail,'quantity'=>1,'type'=>3);
        }
        return $source;
    }

    /**
     * 获取产品字体使用明细
     * @param $product_id
     * @param $product_temp_id
     */
    public function get_product_used_font_detail($product_id){
        $source = array();
        //计算字体价格
        $font_ids = $this->getReSourceIds(
            array(
                array('product_id', '=', $product_id),
                array('type', '=', 2),
                array('state', '=', 1)
            ),
            'font_id'
        );
        $font_ids = array_unique($font_ids);
        foreach ($font_ids as $font_id) {
            $font_path = DB::table('fonts')->where('font_id',$font_id)->value('font_path');
            $font_name = DB::table('fonts')->where('font_id',$font_id)->value('font_name');
            $font_image = DB::table('fonts')->where('font_id',$font_id)->value('font_image');
            if(empty($font_path) || !is_file(public_path('fonts/').$font_path)){
                throw new FontNotFoundException('地址为'.$font_path.'的字体未找到');
            }
            $prices = PreferentialService::getResourcePrice($font_id, 3);
            if ($prices === false || $prices['original_price'] === false || $prices['preferential_price'] === false) {
                throw new PriceErrorException('ID为' . $font_id . '的字体价格异常');
            }
            $source[] = array('resource_id'=>$font_id,'title'=>$font_name,
                'preferential_price'=>GeneralTool::priceFormat($prices['preferential_price']),'original_price'=>GeneralTool::priceFormat($prices['original_price']),
                'thumbnail'=>env('IMG_URL_STD_PREFIX').$font_image,'quantity'=>1,'type'=>4);
        }
        return $source;
    }

    /**
     * 获取产品使用明细
     * @throws FontNotFoundException
     * @throws ImageNotFoundException
     * @throws PriceErrorException
     */
    public function get_product_used_customizations_source_pic_detail($product_id)
    {
        $source = array();
        //获取自定义素材
        $source_pic_ids = $this->getReSourceIds(
            array(
                array('product_id', '=', $product_id),
                array('type', '=', 1), array('image_type', '=', 1),
                array('state', '=', 1)
            ),
            'creative_id'
        );
        $source_pic_ids = array_unique($source_pic_ids);
        foreach ($source_pic_ids as $source_pic_id) {
            //根据ID获取素材详情
            $this->setParameter([
                'table' => 'user_creatives',
                'where' => [['creative_id','=',$source_pic_id],['state','=',1]],
                'select'=> ['thumbnail','name','preferential_price','price as original_price']
            ]);
            $user_creatives = $this->getById();
            if(empty($user_creatives)){
                throw new ImageNotFoundException('素材ID为'.$source_pic_id.',素材类型为1的原图片未找到');
            }
            $source[] = array(
                'resource_id'=>$source_pic_id,
                'title'=>$user_creatives->name,
                'preferential_price'=>$user_creatives->preferential_price,
                'original_price'=>$user_creatives->original_price,
                'thumbnail'=>env('IMG_URL_STD_PREFIX').$user_creatives->thumbnail,
                'quantity'=>1,
                'type'=>2
            );
        }
        return $source;
    }

    /**
     * 获取已上架作品数量
     */
    public function get_collection_create_quantity($user_id,$collection_id){
        $products = DB::table('products')
            ->where([
                'user_id' => $user_id,
                'user_collection_id' => $collection_id,
                'is_shelves'          => 1,
                'state'                => 1
            ])
            ->get()
            ->toArray();
        foreach($products as $key => $product){
            if($product->is_shelves == 1 && ($product->is_infinite_time == 0 && $product->off_shelves_time < time())){
                $product->is_shelves = 0;
                //剔除超出下架时间商品
                array_splice($products,$key,1);
                continue;
            }
        }
        return $this->numFormat(count($products));
    }

    /**
     * 根据用户ID和模板ID获取草稿ID
     * @Author    zhouchao
     * @DateTime  2017-03-13
     * @copyright 2017 QuanZhouYunYiShang Inc.
     * @license   [license]
     * @version   [version]
     * @param     [type]
     * @param     [type]
     * @return    boolean
     */
    public function has_draft_by_product_temp_id($user_id,$product_temp_id)
    {
        $user_type = DB::table('users')->where('user_id', $user_id)->value('user_type');
        if($user_type == 0){
            return [];
        }
        $draft_ids = DB::table('product_drafts')
                       ->where(['user_id'=>$user_id,'product_temp_id'=>$product_temp_id,'state'=>1])
                       ->pluck('product_draft_id')
                       ->toArray();
        return $draft_ids;               
    }

    /**
     * 根据用户ID组获取产品
     * @Author    zhouchao
     * @DateTime  2017-03-13
     * @copyright 2017 QuanZhouYunYiShang Inc.
     * @license   [license]
     * @version   [version]
     * @param     array 
     * @return    array
     */
    public function get_product_ids_by_user_ids($user_ids)
    {
        $product_ids = DB::table('products')
                        ->where(['is_shelves'=>1,'state'=>1,'is_show'=>1])
                        ->whereIn('user_id',$user_ids) 
                        ->pluck('product_id')
                        ->toArray();
        return $product_ids;
    }

    /**
     * 根据产品模板ID组获取作品
     * @Author    zhouchao
     * @DateTime  2017-03-13
     * @copyright 2017 QuanZhouYunYiShang Inc.
     * @license   [license]
     * @version   [version]
     * @param     array
     * @return    array
     */
    public function get_product_ids_by_temp_ids($product_temp_ids)
    {
        $product_ids = DB::table('products')
                        ->where(['is_shelves'=>1,'state'=>1,'is_show'=>1])
                        ->whereIn('product_temp_id',$product_temp_ids) 
                        ->pluck('product_id')
                        ->toArray();
        return $product_ids;
    }

}
